<?php

namespace app\api\controller\store;

use app\api\model\UserCollect;
use app\api\services\CacheServices;
use app\api\services\merchant\MerchantServices;
use app\api\services\store\GoodsCommentServices;
use app\api\services\store\GoodsServices;
use app\common\controller\Api;
use think\Exception;
use think\exception\DbException;

/**
 * 商品控制器
 */
class Goods extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = '*';

    /**
     * 商品列表
     * @return void
     * @throws DbException
     */
    public function list()
    {
        $is_hot = input('is_hot', 0);
        $cid = input('cid');
        $this->paginate(GoodsServices::list($is_hot, $cid));
    }

    public function detail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $this->success(GoodsServices::detail($id, $this->auth->id));
    }

    /**
     * 收藏
     * @return void
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function collect()
    {
        $id = input('goodsId');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $userid = $this->auth->id;
        $lock = CacheServices::get('collect_' . $userid . $id);
        if (!empty($lock)) {
            $this->error('请勿重复收藏');
        }
        CacheServices::set('collect_' . $userid . $id, $id, 5, 'collect');
        $status = false;
        $collect = UserCollect::where('store_goods_id', $id)->where('user_id', $userid)->find();
        if (!$collect) {
            // 收藏
            $status = true;
            UserCollect::create(['store_goods_id' => $id, 'user_id' => $userid]);
        } else {
            // 删除
            $collect->delete();
            $collect->save();
            $status = false;
        }
        $this->success('成功', [
            'status' => $status,
        ]);
    }

    /**
     * 商品评论列表
     * @return void
     */
    public function comment()
    {
        // 分类直接写死
        $id = input('goodsId');
        if (empty($id)) {
            $this->error("参数错误");
        }
        $level = input('level', '');
        $userid = $this->auth->id;
        $this->paginate(GoodsCommentServices::commentList($id, $userid, $level));


    }

    /**
     * 商家详情
     * @return void
     * @throws DbException
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function merchantDetail()
    {
        $id = input('merchant_id');
        $goodsName = input('goods_name');
        if (empty($id)) {
            throw new Exception("参数错误");
        }
        $this->success('成功', MerchantServices::detail($id,$goodsName));

    }
}